from django import template
from django.contrib.contenttypes.models import ContentType

from pygameweb.comments.models import Comment

register = template.Library()

class CommentCountNode(template.Node):
    def __init__(self, obj):
        self.obj = template.Variable(obj)
    def render(self,context):
        try:
            obj = self.obj.resolve(context)
        except template.VariableDoesNotExist:
            return ""
        content_type = ContentType.objects.get_for_model( obj )
        comments = Comment.objects.filter(content_type = content_type, object_id = obj.id )
        context["comments_count"] = comments.count()
        return ""

@register.tag(name="get_comments_count")
def do_get_comments_count(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, obj = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    return CommentCountNode( obj )

@register.simple_tag
def comment_edit_links(request, comment):
    perms = comment.get_user_perms(request.user)        
    if perms[0] or perms[1]:
        form = "<form action='#%s' method='post' class='comment-actions'><p>"
        form += "<input type='hidden' name='comment_id' value='%s'/>" % comment.id
        form += "<input type='submit' name='comment_edit' value='%s' class='button'/>"
        form += "</p></form>"
        out = ""
        if perms[0]:
            out += form % ("editcomment", "edit")
        if perms[1]:
            out += form % ("confirm", "delete")
        
        return out
    return ""

comment_edit_links.allow_tags = True
